package com.ruoyi.project.WxMoudle.Bases;

import com.alibaba.fastjson.JSONObject;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;

import static com.ruoyi.project.WxMoudle.Bases.CommonUtil.httpsRequest;

/**
 * Created by admin on 2017/10/20.
 */
public class WeixinHelper {
    /**
     * 获取网页授权凭证
     *
     * @param appId     公众账号的唯一标识
     * @param appSecret 公众账号的密钥
     * @return getAccessToken
     */
    public static String getAccessToken(String appId, String appSecret) {
        String access_token = null;
        // 拼接请求地址
        String requestUrl = "https://api.weixin.qq.com/cgi-bin/token?appid=APPID&secret=SECRET&grant_type=client_credential";
        requestUrl = requestUrl.replace("APPID", appId);
        requestUrl = requestUrl.replace("SECRET", appSecret);
        // 获取网页授权凭证
        JSONObject jsonObject = httpsRequest(requestUrl, "GET", null);
        if (null != jsonObject) {
            try {
                access_token = jsonObject.getString("access_token");
            } catch (Exception e) {
                access_token = null;
            }
        }
        return access_token;
    }

    /**
     * 获取网页授权凭证
     *
     * @param appId     公众账号的唯一标识
     * @param appSecret 公众账号的密钥
     * @param code
     * @return WeixinAouth2Token
     */
    public static Wxoauth2token getOauth2AccessToken(String appId, String appSecret, String code) {
        Wxoauth2token wat = null;
        // 拼接请求地址
        String requestUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";
        requestUrl = requestUrl.replace("APPID", appId);
        requestUrl = requestUrl.replace("SECRET", appSecret);
        requestUrl = requestUrl.replace("CODE", code);
        // 获取网页授权凭证
        JSONObject jsonObject = httpsRequest(requestUrl, "GET", null);
        for (int i = 0; i < 100; i++) {
            System.out.println(jsonObject);
        }
        if (null != jsonObject) {
            try {
                wat = new Wxoauth2token();
                wat.setAccessToken(jsonObject.getString("access_token"));
                wat.setExpiresIn(Integer.parseInt(jsonObject.getString("expires_in")));//过期时间
                wat.setRefreshToken(jsonObject.getString("refresh_token"));
                wat.setOpenId(jsonObject.getString("openid"));
                wat.setScope(jsonObject.getString("scope"));
                wat.setUpdateTime(new Date());
            } catch (Exception e) {
                wat = null;
            }
        }
        return wat;
    }


    /**
     * 通过网页授权获取用户信息
     *
     * @param accessToken 网页授权接口调用凭证
     * @param openId      用户标识
     * @return SNSUserInfo
     */
    @SuppressWarnings({"deprecation", "unchecked"})
    public static SNSUserInfo getSNSUserInfo(String accessToken, String openId) {

        SNSUserInfo snsUserInfo = null;
        // 拼接请求地址
        String requestUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID";
        requestUrl = requestUrl.replace("ACCESS_TOKEN", accessToken).replace("OPENID", openId);
        // 通过网页授权获取用户信息
        JSONObject jsonObject = httpsRequest(requestUrl, "GET", null);
        if (null != jsonObject) {
            try {
                snsUserInfo = new SNSUserInfo();
                // 用户的标识
                snsUserInfo.setOpenId(openId);
                // 昵称
                snsUserInfo.setNickname(jsonObject.getString("nickname"));
                // 性别（1是男性，2是女性，0是未知）
                snsUserInfo.setSex(jsonObject.getInteger("sex"));
                // 用户所在国家
                snsUserInfo.setCountry(jsonObject.getString("country"));
                // 用户所在省份
                snsUserInfo.setProvince(jsonObject.getString("province"));
                // 用户所在城市
                snsUserInfo.setCity(jsonObject.getString("city"));
                // 用户头像
                snsUserInfo.setHeadImgUrl(jsonObject.getString("headimgurl"));
                // 用户特权信息
                snsUserInfo.setPrivilegeList((List) jsonObject.get("privilege"));
            } catch (Exception e) {
                snsUserInfo = null;
//                int errorCode = jsonObject.getInteger("errcode");
//                String errorMsg = jsonObject.getString("errmsg");
            }
            return snsUserInfo;
        } else {
            return null;
        }
    }

    /**
     * 发送模板消息
     * appId 公众账号的唯一标识
     * appSecret 公众账号的密钥
     * openId 用户标识
     */
    public static Object sendTemplateMessage(String body) {
        String access_token = WeixinHelper.getAccessToken(WeixinConfig.APPID, WeixinConfig.APPSECRET);
        try {
            body = URLDecoder.decode(body, "UTF-8").replaceAll("=", "");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + access_token;

        JSONObject jsonObject = CommonUtil.httpRequest(url, "POST", body);
        System.out.println(jsonObject);
        int result = 0;
        if (null != jsonObject) {
            if (0 != jsonObject.getInteger("errcode")) {
                result = jsonObject.getInteger("errcode");
                return result;
            }
        }
        return result;
    }

    /**
     * @param touser
     * @param first
     * @param keyword1
     * @param keyword2
     * @param remark
     * @return
     */
    public static String parameterToJson(String touser, String first,
                                         String keyword1, String keyword2, String remark) {
        return String.format("{ \"touser\": \"%s\"," +
                        " \"template_id\": \"-i-f4_wtR0zYeJJdZkB6vdvkUn8GtXV3IaofR0rYVlI\", \"data\": {" +
                        " \"first\": { \"value\": \"%s\", \"color\": \"#173177\" }," +
                        " \"keyword1\": { \"value\": \"%s\", \"color\": \"#173177\" }," +
                        " \"keyword2\": { \"value\": \"%s\", \"color\": \"#173177\" }," +
                        " \"remark\": { \"value\": \"%s\", \"color\": \"#173177\" } } }",
                touser, first, keyword1, keyword2, remark);
    }

}
